package com.lewis.way.test;

import com.lewis.way.result.R;
import org.apache.jmeter.config.Arguments;
import org.apache.jmeter.protocol.java.sampler.AbstractJavaSamplerClient;
import org.apache.jmeter.protocol.java.sampler.JavaSamplerContext;
import org.apache.jmeter.samplers.SampleResult;

import java.nio.charset.StandardCharsets;

public class JavaWithArgs extends AbstractJavaSamplerClient {

    private long startTime;
    private long endTime;
    private long duration;

    @Override
    public Arguments getDefaultParameters() {
        Arguments args = new Arguments();
        args.addArgument("name", "World");
        return args;
    }

    @Override
    public void setupTest(JavaSamplerContext context) {
        startTime = System.currentTimeMillis();
    }

    @Override
    public void teardownTest(JavaSamplerContext context) {
        endTime = System.currentTimeMillis();
        duration = endTime - startTime;
    }

    @Override
    public SampleResult runTest(JavaSamplerContext context) {
        SampleResult result = new SampleResult();
        result.sampleStart();

        R r = R.builder().build();
        try {
            Thread.sleep(1);
            result.setSuccessful(true);
            r.setCode("200");
            r.setResult("Hello " + context.getParameter("name") + "!");
        } catch (InterruptedException e) {
            result.setSuccessful(false);
            r.setCode("500");
            r.setResult(e.getLocalizedMessage());
        }
        result.sampleEnd();

        r.setStartTime(startTime);
        r.setEndTime(endTime);
        r.setDuration(endTime - startTime);

        result.setResponseCode("OK");
        result.setResponseMessage(r.toString());
        result.setResponseData(r.toString().getBytes(StandardCharsets.UTF_8));
        return result;
    }

}
